package sim.ring.technical.xml;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import sim.ring.method.Method;

public class XmlParser extends DefaultHandler {

	private String temp;
	private ArrayList<Method> methods= new ArrayList<Method>();
	private String currentElement="";
	private int stage=0;
	private String classification="";
	private String shortNotation="";
	private String name="";

	
	public ArrayList<Method> parse() throws IOException, SAXException,ParserConfigurationException {
		SAXParserFactory spfac = SAXParserFactory.newInstance();
		SAXParser sp = spfac.newSAXParser();
		XmlParser handler = new XmlParser();
		sp.parse("bin/allmeths.xml", handler);
		return handler.getMethods();
	}

	public void characters(char[] buffer, int start, int length) {
		temp = new String(buffer, start, length);
	}
       
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		temp = "";
		if (qName.equalsIgnoreCase("METHOD")) {
			currentElement=qName;
		} else if (qName.equalsIgnoreCase("METHODSET")) {
			currentElement=qName;
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {    	   
		if(currentElement.equalsIgnoreCase("METHOD")) {
			if (qName.equalsIgnoreCase("METHOD")&&stage<10) {
				methods.add(new Method(name,classification,stage,shortNotation));
			} else if (qName.equalsIgnoreCase("NOTATION")) {
				shortNotation=temp;
			} else if (qName.equalsIgnoreCase("NAME")) {
				name=temp;
			} else if (qName.equalsIgnoreCase("CLASSIFICATION") && temp!="" && temp!=null) {
				classification=temp;
			} 
		} else if(currentElement.equalsIgnoreCase("METHODSET")) {
			if (qName.equalsIgnoreCase("STAGE")) {
				stage=Integer.parseInt(temp);
			} else if (qName.equalsIgnoreCase("CLASSIFICATION")) {
				classification=temp;
			}
		}
	}
	
	private ArrayList<Method> getMethods() {
		return methods;
	}
}
